package web.servlet;

import domain.Account;
import domain.Cart;
import domain.CartItem;
import domain.Item;
import service.CartService;
import service.CatalogService;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

public class AddItemToCartServlet extends HttpServlet {

    private static final String CART_FORM = "/WEB-INF/jsp/cart/cart.jsp";

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String workingItemId = req.getParameter("workingItemId");
        HttpSession session = req.getSession();
        //如果是第一次点开，cart都没有new出来，也没有加到会话中；如果是再次点开修改，那么会话中已经包含了一个cart对象了，要把它拿出来并在原有的基础上修改
        Cart cart = (Cart) session.getAttribute("cart");
        //用户操作还有cartservice
        //token=>都是为了filter准备的
        Account account=(Account)session.getAttribute("loginAccount");
        CartService cartService=new CartService();


        if (cart == null)
        {
            cart = new Cart();//所以先new一个cart
        }

        if (cart.containsItemId(workingItemId)) //是否包含当前要加入的id
        {
            cart.incrementQuantityByItemId(workingItemId);
            if(account!=null){
                cartService.increaseQuantityByItemId(workingItemId,account.getUsername());
            }
        }
        else
        {
            CatalogService catalogService=new CatalogService();
            boolean isInStock = catalogService.isItemInStock(workingItemId);
            Item item = catalogService.getItem(workingItemId);
            cart.addItem(item, isInStock);
            if(account!=null){
                int size=cart.getCartItemList().size();
                CartItem cartItem=cart.getCartItemList().get(size-1);
                if(cartService.isItemInCart(workingItemId,account.getUsername())){
                    CartItem cartItem1=cartItem;
                    cartItem1.setQuantity(1);
                    cartService.insertExistItemInCart(cartItem1,account.getUsername());
                }else{
                    cartService.insertCartItemInCart(cartItem,account.getUsername());
                }
            }
        }
        //补充token
        session.setAttribute("cart", cart);//把处理完的cart放回到session中
        req.getRequestDispatcher(CART_FORM).forward(req, resp);
    }
}